import { showSuccessToast } from 'vant';
import { ref } from 'vue';
import { useRoute } from 'vue-router';

import { deserialize } from '@/plugins/reflect-metadata';

import { getAuthStatus } from '../api';
import RealAuth from '../models/RealAuth';

const useRealAuthCallback = () => {
  const route = useRoute();

  const state = ref<{ data: RealAuth; loading: boolean }>({
    data: new RealAuth(),
    loading: false,
  });

  const pageState = ref({
    error: !state.value.data.response.extInfo.certifyId,
    description: 'certifyId 实名认证失败，请检查网络',
  });

  const verifyState = ref<any>({});

  // ?response=success&code=1000&subCode=Z5050&reason=人脸验证成功&certifyId=123
  const handleInit = () => {
    try {
      const { response } = route.query;
      const resultData = deserialize({ response: JSON.parse(response as string) }, RealAuth);
      state.value.data = resultData;
    } catch (error) {
      // console.log(error);
    }
  };

  const initFaceVerify = async () => {
    try {
      state.value.loading = true;

      const { data } = await getAuthStatus(state.value.data.response.extInfo.certifyId);
      verifyState.value = data;
      showSuccessToast(data.msg || '实名认证验证成功');
    } catch (error) {
      //
    } finally {
      state.value.loading = false;
    }
  };
  return {
    state,
    pageState,
    verifyState,
    handleInit,
    initFaceVerify,
  };
};

export default useRealAuthCallback;
